package com.atguigu.yygh.order.controller;

import com.atguigu.rabbit.consts.MqConst;
import com.atguigu.rabbit.service.RabbitService;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WeixinService;
import com.atguigu.yygh.vo.msm.MsmVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author:ahang
 * @create:2022-09-16 10:12
 * @Description:
 */
@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RabbitService rabbitService;

    //生成二维码
    @GetMapping("/createNative/{orderId}")
    public R createNative(@PathVariable("orderId") Long orderId) {
        Map map = weixinService.createNative(orderId);
        return R.ok().data(map);
    }

    @GetMapping("queryPayStatus/{orderId}")
    public R queryPayStatus( @PathVariable("orderId") Long orderId){
        Map<String,String> map = weixinService.queryPayStatus(orderId);
        //校验微信查询状态接口的返回值
        if(map == null){
            return R.error().message("支付出错");
        }

        //支付成功后修改平台数据源
        if("SUCCESS".equals(map.get("trade_state"))){
            String out_trade_no = (String) map.get("out_trade_no");
            paymentService.paySuccess(out_trade_no,map);

            //支付成功后通过mq发送短信通知
            MsmVo msmVo = new MsmVo();
            OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);
            String patientPhone = orderInfo.getPatientPhone();
            msmVo.setTemplateCode(patientPhone);
//            msmVo.setTemplateCode("");
            msmVo.getParam().put("message","支付成功");

            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,msmVo);


            return R.ok().message("支付成功");
        }

        return R.ok().message("支付中");//
    }
}
